/**
 *
 */
package com.nightwalker.xsite.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.nightwalker.xsite.bean.AutorBean;
import com.nightwalker.xsite.infra.ErroGraveException;

/**
 * AutorDao
 * <br><br>
 * <b>Description:</b>Classe que gerencia os acessos a dados relacionados a
 * autores.
 * <br><br>
 * Created in Jan 29, 2008 11:50:28 PM
 * <br>
 * <b>version:</b>
 * <br>
 * <b>Modifications:</b>
 */
public class AutorDao extends Dao{

	public AutorBean recuperarAutores(AutorBean autor){

		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		StringBuilder query = new StringBuilder("SELECT id, nome FROM autores");

		try {
			log.debug("Consultando autores(preparedStatment): "+ query.toString());

			preparedStatement = conexao.prepareStatement(query.toString());
			resultSet = preparedStatement.executeQuery();

			List<AutorBean> autores = autor.getAutores();

			AutorBean autorOut;


			while (resultSet.next()){
				autorOut = new AutorBean();
				autorOut.setId(resultSet.getString("id"));
				autorOut.setNome(resultSet.getString("nome"));

				autores.add(autorOut);
			}

			log.info("Foram encontrados " + autores.size() + " autores");

			return autor;


		} catch (SQLException e) {
			log.error("Erro ao recuperar os autores: ", e);
			throw new ErroGraveException(e);
		} finally {
			try {
				if (resultSet != null){
					resultSet.close();
				}

				if (preparedStatement != null){
					preparedStatement.close();
				}

			} catch (SQLException e) {
				log.error("Erro ao fechar resultSet ou statment: ", e);
			}
		}
	}

	public int incluirAutor(AutorBean autor){
		PreparedStatement preparedStatement = null;

		StringBuilder query = new StringBuilder("insert into autores (nome) value (?)");

		try {
			log.debug("Incluindo autor(preparedStatment): "+ query.toString());
			preparedStatement = conexao.prepareStatement(query.toString());

			preparedStatement.setString(1, autor.getNome());

			return preparedStatement.executeUpdate();

		} catch (SQLException e) {
			log.error("Erro ao inserir autor: ", e);
			throw new ErroGraveException(e);
		} finally {
			try {
				if (preparedStatement != null){
					preparedStatement.close();
				}

			} catch (SQLException e) {
				log.error("Erro ao fechar statment: ", e);
			}
		}
	}
}
